//Copyright (C) 2009 Ron Coleman. Contact: ronncoleman@gmail.com
//
//This library is free software; you can redistribute it and/or
//modify it under the terms of the GNU General Public License
//as published by the Free Software Foundation; either
//version 3 of the License, or (at your option) any later version.
//
//This library is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
//General Public License for more details.
//
//You should have received a copy of the GNU General Public License
//along with this library; if not, write to the Free Software
//Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA

package org.workplicity.cia.ui.android;

import java.util.ArrayList;

import org.workplicity.cia.listener.ActionBarSpinnersListener;
import org.workplicity.cia.model.LocalWorkRequest;
import org.workplicity.cia.model.User;
import org.workplicity.cia.ui.android.ElogEditActivity;
import org.workplicity.cia.util.AndroidHelper;
import org.workplicity.elog.entry.Elog;
import org.workplicity.elog.entry.ElogUser;
import org.workplicity.task.NetTask;
import org.workplicity.util.Helper;
import org.workplicity.worklet.WorkletContext;

import com.mongodb.BasicDBObject;
import com.mongodb.util.JSON;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ObjectAnimator;
import android.animation.PropertyValuesHolder;
import android.animation.ValueAnimator;
import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.app.PendingIntent;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.SpinnerAdapter;
import android.widget.Toast;

/**
 * 
 * @author Brian Gormanly
 *
 */

public class MainActivity extends Activity implements ActionBar.OnNavigationListener {

    private static final int NOTIFICATION_DEFAULT = 1;
    private static final String ACTION_DIALOG = "org.workplicity.cia.ui.action.DIALOG";

    private View mActionBarView;
    private Animator mCurrentTitlesAnimator;
    private int mLabelIndex = 1;
    private int mThemeId = -1;
    
    
    private ArrayList<ElogUser> users;
    public String[] userNames = null;
    
    
    private ElogUser userInView = null;
    
    
    private long end;

    private long start;
    
    private Button logDetailsButton;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if(savedInstanceState != null && savedInstanceState.getInt("theme", -1) != -1) {
            mThemeId = savedInstanceState.getInt("theme");
            this.setTheme(mThemeId);
        }
        else {
        	// default
        	this.setTheme(R.style.AppTheme_Light);
        }

        setContentView(R.layout.main);

        ActionBar bar = getActionBar();
        
        // get the resourcess available
        Resources res = getResources();
        mActionBarView = getLayoutInflater().inflate(R.layout.action_bar_custom, null);

        bar.setCustomView(mActionBarView);
        bar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM | ActionBar.DISPLAY_USE_LOGO);
        bar.setDisplayShowHomeEnabled(true);
        
        
        // User list spinner
        Spinner userSpinner = (Spinner) findViewById(R.id.userSpinner);
        ArrayAdapter<CharSequence> userAdapter = ArrayAdapter.createFromResource(this, R.array.user_array, android.R.layout.simple_spinner_item);
        userAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);    
        userSpinner.setAdapter(userAdapter);
        userSpinner.setOnItemSelectedListener(new ActionBarSpinnersListener());
        
        // Type spinner
        Spinner typeSpinner = (Spinner) findViewById(R.id.typeSpinner);
        ArrayAdapter<CharSequence> typeAdapter = ArrayAdapter.createFromResource(this, R.array.type_array, android.R.layout.simple_spinner_item);
        typeAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        typeSpinner.setAdapter(typeAdapter);
        typeSpinner.setOnItemSelectedListener(new ActionBarSpinnersListener());
        
        // Status spinner
        Spinner statusSpinner = (Spinner) findViewById(R.id.statusSpinner);
        ArrayAdapter<CharSequence> statusAdapter = ArrayAdapter.createFromResource(this, R.array.status_array, android.R.layout.simple_spinner_item);
        statusAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        statusSpinner.setAdapter(statusAdapter);
        statusSpinner.setOnItemSelectedListener(new ActionBarSpinnersListener());
        
        // Age spinner
        Spinner ageSpinner = (Spinner) findViewById(R.id.ageSpinner);
        ArrayAdapter<CharSequence> ageAdapter = ArrayAdapter.createFromResource(this, R.array.age_array, android.R.layout.simple_spinner_item);
        ageAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        
        ageSpinner.setAdapter(ageAdapter);
        
        ageSpinner.setOnItemSelectedListener(new ActionBarSpinnersListener());
        
        WorkletContext context = WorkletContext.getInstance();
        
        AndroidHelper.login("admin", "gaze11e", context);
        
        // get all the users
        String criteria = JSON.serialize(new BasicDBObject("entry.id",new BasicDBObject("$gte",0)));

        users = AndroidHelper.query(NetTask.REPOS_ACCOUNTS, criteria, context);
        
        
        
        //ArrayList<Elog> elogs = new ArrayList<Elog>( );
        
     
        
        
        
        
        
        
        
        
        // create and manage the click event of the detials button
        this.logDetailsButton = (Button)this.findViewById(R.id.logDetailsButton);
        this.logDetailsButton.setOnClickListener(new OnClickListener() {
          @Override
          public void onClick(View v) {
        	  Intent myIntent = new Intent(MainActivity.this, ElogEditActivity.class);
              startActivityForResult(myIntent, 0);
          }
        });
        
        
        
        
        // initial test of connecting to the server and bringing back data
        ArrayList<User> users = new ArrayList<User>( );
        
        ArrayList<String> elogNames = new ArrayList<String>( );
        ArrayList<Integer> elogSizes = new ArrayList<Integer>( );
        
        elogNames.clear();
        elogSizes.clear();
        
        
        
        
    }
    
    
    public void updateUsers(ArrayList<ElogUser> users) {
    	this.users = users;
    	for(int i=0; i<users.size(); i++) {
    		this.userNames[i] = users.get(i).getFirstName() + " " + users.get(i).getLastName();
    	}
    	this.refresh();
    }
    
    public void refresh() {
    	Spinner userSpinner = (Spinner)findViewById(R.id.userSpinner);
    	ArrayAdapter<String> userAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, userNames);

        userAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);    
        userSpinner.setAdapter(userAdapter);
        userSpinner.setOnItemSelectedListener(new ActionBarSpinnersListener());
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.main_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {

        case R.id.toggleTitles:
            toggleVisibleTitles();
            return true;

        case R.id.toggleTheme:
            if (mThemeId == R.style.AppTheme_Dark) {
                mThemeId = R.style.AppTheme_Light;
            } else {
                mThemeId = R.style.AppTheme_Dark;
            }
            this.recreate();
            return true;

        case R.id.showHelpDialog:
            showDialog("CIAElog is a branch of Workplicity.\nThis is an example help dialog box that will contain information on how to use the screen you are looking at.");
            return true;
            
        case R.id.showAboutDialog:
            showDialog("CIAElog is a branch of Workplicity.\nAndroid Client for CIAElog Version 1.0\n\nContributors:\nBrian Gormanly");
            return true;

        default:
            return super.onOptionsItemSelected(item);
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        if (ACTION_DIALOG.equals(intent.getAction())) {
            showDialog(intent.getStringExtra(Intent.EXTRA_TEXT));
        }
    }

    void showDialog(String text) {
        // DialogFragment.show() will take care of adding the fragment
        // in a transaction.  We also want to remove any currently showing
        // dialog, so make our own transaction and take care of that here.
        FragmentTransaction ft = getFragmentManager().beginTransaction();

        DialogFragment newFragment = MyDialogFragment.newInstance(text);

        // Show the dialog.
        newFragment.show(ft, "dialog");
    }

    void showNotification(boolean custom) {
        
    }

    PendingIntent getDialogPendingIntent(String dialogText) {
        return PendingIntent.getActivity(
                this,
                dialogText.hashCode(), // Otherwise previous PendingIntents with the same
                                       // requestCode may be overwritten.
                new Intent(ACTION_DIALOG).putExtra(Intent.EXTRA_TEXT, dialogText).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK), 0);
    }

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        
        return true;
    }

    @Override
    public void onSaveInstanceState (Bundle outState) {
        super.onSaveInstanceState(outState);
        ActionBar bar = getActionBar();
        int category = bar.getSelectedTab().getPosition();
        outState.putInt("category", category);
        outState.putInt("theme", mThemeId);
    }


    public static class MyDialogFragment extends DialogFragment {

        public static MyDialogFragment newInstance(String title) {
            MyDialogFragment frag = new MyDialogFragment();
            Bundle args = new Bundle();
            args.putString("text", title);
            frag.setArguments(args);
            return frag;
        }

        @Override
        public Dialog onCreateDialog(Bundle savedInstanceState) {
            String text = getArguments().getString("text");

            return new AlertDialog.Builder(getActivity()).setTitle("CIAElog Ver. 1")
                    .setMessage(text)
                    .setPositiveButton(android.R.string.ok,
                            new DialogInterface.OnClickListener() {
                                @Override
								public void onClick(DialogInterface dialog, int whichButton) {
                                }
                            }).create();
        }
    }


	@Override
	public boolean onNavigationItemSelected(int itemPosition, long itemId) {
		// Do Something
		
		String a = "testing";
	    
		return false;
	}
	
	
	
	
	
	
	public void toggleVisibleTitles() {
        // Use these for custom animations.
        final FragmentManager fm = getFragmentManager();
        final TitlesFragment f = (TitlesFragment) fm.findFragmentById(R.id.frag_title);
        final View titlesView = f.getView();
        mLabelIndex = 1 - mLabelIndex;

        // Determine if we're in portrait, and whether we're showing or hiding the titles
        // with this toggle.
        final boolean isPortrait = getResources().getConfiguration().orientation ==
                Configuration.ORIENTATION_PORTRAIT;

        final boolean shouldShow = f.isHidden() || mCurrentTitlesAnimator != null;

        // Cancel the current titles animation if there is one.
        if (mCurrentTitlesAnimator != null)
        	mCurrentTitlesAnimator.cancel();

        // Begin setting up the object animator. We'll animate the bottom or right edge of the
        // titles view, as well as its alpha for a fade effect.
        ObjectAnimator objectAnimator = ObjectAnimator.ofPropertyValuesHolder( titlesView,
                PropertyValuesHolder.ofInt(isPortrait ? "bottom" : "right", shouldShow ? getResources().getDimensionPixelSize(R.dimen.titles_size) : 0),
                PropertyValuesHolder.ofFloat("alpha", shouldShow ? 1 : 0)
        );

        // At each step of the animation, we'll perform layout by calling setLayoutParams.
        final ViewGroup.LayoutParams lp = titlesView.getLayoutParams();
        objectAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
			public void onAnimationUpdate(ValueAnimator valueAnimator) {
                // *** WARNING ***: triggering layout at each animation frame highly impacts
                // performance so you should only do this for simple layouts. More complicated
                // layouts can be better served with individual animations on child views to
                // avoid the performance penalty of layout.
                if (isPortrait) {
                    lp.height = (Integer) valueAnimator.getAnimatedValue();
                } else {
                    lp.width = (Integer) valueAnimator.getAnimatedValue();
                }
                titlesView.setLayoutParams(lp);
            }
        });

        if (shouldShow) {
            fm.beginTransaction().show(f).commit();
            objectAnimator.addListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animator) {
                    mCurrentTitlesAnimator = null;
                }
            });

        } else {
            objectAnimator.addListener(new AnimatorListenerAdapter() {
                boolean canceled;

                @Override
                public void onAnimationCancel(Animator animation) {
                    canceled = true;
                    super.onAnimationCancel(animation);
                }

                @Override
                public void onAnimationEnd(Animator animator) {
                    if (canceled)
                        return;
                    mCurrentTitlesAnimator = null;
                    fm.beginTransaction().hide(f).commit();
                }
            });
        }

        // Start the animation.
        objectAnimator.start();
        mCurrentTitlesAnimator = objectAnimator;

        invalidateOptionsMenu();

        // Manually trigger onNewIntent to check for ACTION_DIALOG.
        onNewIntent(getIntent());
	}
	
	
	
	
	
	/*
	
    
    
    
    @Override
	public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) {
        TitlesFragment titleFrag = (TitlesFragment) getFragmentManager().findFragmentById(R.id.frag_title);
        titleFrag.populateTitles(tab.getPosition());

        titleFrag.selectPosition(0);
    }

    @Override
	public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction ft) {
    }

    @Override
	public void onTabReselected(ActionBar.Tab tab, FragmentTransaction ft) {
    }
    
    */
}
